import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class UserConfig {
  static final UserConfig _instance = UserConfig._internal();
  factory UserConfig() => _instance;
  UserConfig._internal();

  static const String _keyApiConfig = 'user_api_config';
  static const String _keyEnabled = 'user_config_enabled';

  bool _initialized = false;
  Map<String, dynamic>? _apiConfig;
  bool _enabled = false;

  /// 初始化用户配置
  Future<void> init() async {
    if (_initialized) return;

    final prefs = await SharedPreferences.getInstance();

    // 加载配置启用状态
    _enabled = prefs.getBool(_keyEnabled) ?? false;

    // 加载API配置
    final apiConfigStr = prefs.getString(_keyApiConfig);
    if (apiConfigStr != null) {
      try {
        _apiConfig = json.decode(apiConfigStr);
      } catch (e) {
        print('解析API配置出错: $e');
      }
    }

    _initialized = true;
  }

  /// 是否启用用户配置
  bool get isEnabled => _enabled;

  /// 获取用户API配置
  Map<String, dynamic>? get apiConfig => _apiConfig;

  /// 设置用户API配置
  Future<void> setApiConfig(Map<String, dynamic>? config) async {
    _apiConfig = config;
    final prefs = await SharedPreferences.getInstance();
    if (config != null) {
      await prefs.setString(_keyApiConfig, json.encode(config));
    } else {
      await prefs.remove(_keyApiConfig);
    }
  }

  /// 启用或禁用用户配置
  Future<void> setEnabled(bool enabled) async {
    _enabled = enabled;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_keyEnabled, enabled);
  }

  /// 清除所有用户配置
  Future<void> clear() async {
    _apiConfig = null;
    _enabled = false;
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_keyApiConfig);
    await prefs.remove(_keyEnabled);
  }

  /// 验证API配置格式
  static bool validateApiConfig(Map<String, dynamic> config) {
    return config.containsKey('host') &&
        config.containsKey('port') &&
        config.containsKey('protocol') &&
        config.containsKey('path_prefix');
  }
}
